<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-13
 * Time: 上午10:11
 */

namespace api\modules\chedai\controllers;


use api\modules\chedai\tools\ApiTools;
use common\models\credit_app\OrderAttachment;
use common\models\credit_app\OrderCert;
use common\models\credit_app\OrderOwner;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;
use yii\db\Exception;

class OwnerController extends Controller
{
    /**
     * 修改购车人信息
     * @desc post 一般ot开头
     * @param int $order_id 客户订单号
     */
    public function actionSave($order_id)
    {
        $order = $this->_getOrder($order_id);
        if (!$order){
            throw new ErrorException("没有找到客户订单!");
        }
        $owner = $order->owner;
        $cert_vip = $order->certVip;
        $attachment = $order->attachment;
        if (!$owner){
            throw new ErrorException("没有找到购车人信息!");
        }
        if (!$cert_vip){
            throw new ErrorException("没有找到购车人本人征信信息!");
        }
        if (!$attachment){
            throw new ErrorException("没有找到附件信息!");
        }
        $owner->load(ApiTools::setSerializeApiField(\Yii::$app->request->post(),OrderOwner::$serialize_fields), '');
        $cert_vip->load(ApiTools::setSerializeApiField(\Yii::$app->request->post(), OrderCert::$serialize_fields), '');
        $attachment->load(ApiTools::setSerializeApiField(\Yii::$app->request->post(), OrderAttachment::$serialize_fields), '');
        $trans = \Yii::$app->db_app->beginTransaction();
        try{
            $owner->save(false);
            $cert_vip->save(false);
            $attachment->save(false);
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
        $o['order'] = $order->toArray();
        $o['cert_vip'] = ApiTools::showSerializeApiField($cert_vip->toArray(), OrderCert::$serialize_fields);
        $o['owner'] = ApiTools::showSerializeApiField($owner->toArray(), OrderOwner::$serialize_fields);
        $o['attachment'] = ApiTools::showSerializeApiField($attachment->toArray(), OrderAttachment::$serialize_fields);
        return $o;
    }

    private function _getOrder($order_id)
    {
        return \common\models\credit_app\Order::findActiveOneById($order_id);
    }
}